<?php

require_once dirname(__FILE__) . '/SQLHelper.php';

/**
 * Description of SimpleSelect
 *
 * @author Rino7
 */
class SimpleSelect {

    private $_tableName;
    private $_fields;
    private $_orderField;
    private $_sort;
    private $_limit = null;
    private $_offset = null;
    private $_outputQuery = "";
    private $_filters = array();
    private $_results;
    private $_countResults = 0;

    public function __construct($tableName = "") {
        $this->_tableName = $tableName;
    }

    public function from($tableName) {
        $this->_tableName = $tableName;
        return $this;
    }

    /**
     * Set the filters for the query. 
     * 	i.e.: array("fieldName" => array(
     * 	"operator"=>"Utils::EQUALS | Utils::NOT_EQUALS | Utils::LOWER_THAN |", 
     * 	"valueToCompare"=>"theValueToCompareWith"));
     * @see Utils.php
     * @param array $filters 
     */
    public function where(array $filters) {
        $this->_filters = $filters;
        return $this;
    }

    /**
     * Set the fields to return.
     * @example array("nameInTheDb" => "alias")
     * @param array $fields 
     */
    public function select(array $fields) {
        $this->_fields = $fields;
        return $this;
    }

    /**
     * The field to order. Could be only one.
     * @param string $orderField 
     */
    public function orderBy($orderField, $sort = 'ASC') {
        $this->_orderField = $orderField;
        $this->_sort = $sort;
        return $this;
    }

    public function limit(int $limit, $offset = 0) {
        $this->_limit = $limit;
        $this->_offset = $offset;
        return $this;
    }


    private function _prepareSqlQuery() {
        if (!empty($this->_fields)) {
            $this->_outputQuery = "SELECT ";
            $this->_outputQuery .= $this->_prepareFields();
            $this->_outputQuery .= " FROM " . $this->_tableName;
            $this->_outputQuery .= $this->_prepareFilters();
            $this->_outputQuery .= $this->_prepareSort();
            $this->_outputQuery .= $this->_prepareLimits();
        } else {
            throw new Exception("Fields can't be empty");
        }
    }

    private function _prepareFields() {
        $outputFields = "";
        $counter = 0;
        foreach ($this->_fields as $name => $alias) {
            $fieldName = (is_integer($name)) ? $alias : $name;
            $comma = ($counter > 0) ? ", " : "";

            $outputFields .= $comma . $fieldName;
            if (!is_integer($name) && !empty($alias)) {
                $outputFields .= " as " . $alias;
            }
            $counter++;
        }
        return $outputFields;
    }

    private function _prepareFilters() {
        $outputFilters = "";
        if (!empty($this->_filters)) {
            $outputFilters = " WHERE ";
            $counter = 0;
            foreach ($this->_filters as $key => $parameters) {
                if ($counter > 0) {
                    $and = " AND ";
                }
                $outputFilters .= $and . $key . $parameters["operator"] . $parameters["valueToCompare"];
                $counter++;
            }
        }
        return $outputFilters;
    }

    private function _prepareSort() {
        $outputSort = "";
        if (!empty($this->_orderField)) {
            $outputSort = " ORDER BY ";
            $outputSort .= $this->_orderField;
            $outputSort .= " " . $this->_sort;
        }
        return $outputSort;
    }

    private function _prepareLimits() {
        $outputLimits = "";
        if (isset($this->_limit)) {
            $outputLimits = " LIMIT ";
            $outputLimits .= $this->_limit;
            if (isset($this->_offset)) {
                $outputLimits .= ", " . $this->_offset;
            }
        }
        return $outputLimits;
    }

    public function execute() {
        $this->_prepareSqlQuery();
        if(!empty($this->_outputQuery)) {
            $this->_results = SQLHelper::getInstance()->executeSelectQuery($this->_outputQuery);
        }
        
        if(!$this->_results) {
            die('Error al ejecutar la query: <b>' . $this->_outputQuery . '</b>');
        }
    }

    public function getResultsAsObjectArray() {
        $this->execute();
        $associativeResults = array();
        if ($this->_results) {
            $results = $this->_results;
            $index = 0;
            $fieldNames = $results->fetch_fields();
            if ($results) {
                while ($row = $results->fetch_row()) {
                    for ($i = 0; $i < $results->field_count; $i++) {
                        $associativeResults[$index]->{$fieldNames[$i]->name} = $row[$i];
                    }
                    $index++;
                }
                $results->close();
            }
        }
        return $associativeResults;
    }

    /**
     * @TODO: implements this method
     * @param array $config 
     */
    public function quickConfiguration(array $config) {
        
    }

}

?>
